package com.example.service.service.impl;

import com.example.service.entity.SystemTenant;
import com.example.service.repository.SystemTenantRepository;
import com.example.service.service.SystemTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 租户服务实现类
 * 
 * @author example
 * @since 1.0.0
 */
@Service
public class SystemTenantServiceImpl implements SystemTenantService {

    private final SystemTenantRepository tenantRepository;

    @Autowired
    public SystemTenantServiceImpl(SystemTenantRepository tenantRepository) {
        this.tenantRepository = tenantRepository;
    }

    @Override
    @Transactional
    public SystemTenant createTenant(SystemTenant tenant) {
        // 检查租户名称是否已存在
        if (isTenantNameExists(tenant.getName())) {
            throw new IllegalArgumentException("租户名称已存在");
        }
        
        // 检查租户邮箱是否已存在
        if (tenant.getEmail() != null && !tenant.getEmail().isEmpty() && isTenantEmailExists(tenant.getEmail())) {
            throw new IllegalArgumentException("租户邮箱已存在");
        }
        
        // 检查租户电话是否已存在
        if (tenant.getPhone() != null && isTenantPhoneExists(tenant.getPhone())) {
            throw new IllegalArgumentException("租户电话已存在");
        }
        
        // 设置默认值
        if (tenant.getStatus() == null) {
            tenant.setStatus((short) 1); // 默认状态为正常
        }
        
        if (tenant.getIsDeleted() == null) {
            tenant.setIsDeleted(0); // 默认未删除
        }
        
        if (tenant.getPermissionUserCount() == null) {
            tenant.setPermissionUserCount(0); // 默认授权用户数为0
        }
        
        if (tenant.getReadyUserCount() == null) {
            tenant.setReadyUserCount(0); // 默认已用用户数为0
        }
        
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        tenant.setCreatedAt(now);
        tenant.setUpdatedAt(now);
        
        return tenantRepository.save(tenant);
    }

    @Override
    @Transactional
    public SystemTenant updateTenant(SystemTenant tenant) {
        // 检查租户是否存在
        Optional<SystemTenant> existingTenant = tenantRepository.findById(tenant.getId());
        if (existingTenant.isEmpty()) {
            throw new IllegalArgumentException("租户不存在");
        }
        
        // 检查租户名称是否已被其他租户使用
        Optional<SystemTenant> tenantWithSameName = tenantRepository.findByName(tenant.getName());
        if (tenantWithSameName.isPresent() && !tenantWithSameName.get().getId().equals(tenant.getId())) {
            throw new IllegalArgumentException("租户名称已被其他租户使用");
        }
        
        // 检查租户邮箱是否已被其他租户使用
        if (tenant.getEmail() != null && !tenant.getEmail().isEmpty()) {
            Optional<SystemTenant> tenantWithSameEmail = tenantRepository.findByEmail(tenant.getEmail());
            if (tenantWithSameEmail.isPresent() && !tenantWithSameEmail.get().getId().equals(tenant.getId())) {
                throw new IllegalArgumentException("租户邮箱已被其他租户使用");
            }
        }
        
        // 检查租户电话是否已被其他租户使用
        if (tenant.getPhone() != null) {
            Optional<SystemTenant> tenantWithSamePhone = tenantRepository.findByPhone(tenant.getPhone());
            if (tenantWithSamePhone.isPresent() && !tenantWithSamePhone.get().getId().equals(tenant.getId())) {
                throw new IllegalArgumentException("租户电话已被其他租户使用");
            }
        }
        
        // 保留原有的一些字段
        SystemTenant existing = existingTenant.get();
        tenant.setCreatedAt(existing.getCreatedAt());
        tenant.setCreatedBy(existing.getCreatedBy());
        
        // 设置更新时间
        tenant.setUpdatedAt(LocalDateTime.now());
        
        return tenantRepository.save(tenant);
    }

    @Override
    public Optional<SystemTenant> findTenantById(Long id) {
        return tenantRepository.findById(id);
    }

    @Override
    public Optional<SystemTenant> findTenantByName(String name) {
        return tenantRepository.findByName(name);
    }

    @Override
    public Optional<SystemTenant> findTenantByEmail(String email) {
        return tenantRepository.findByEmail(email);
    }

    @Override
    public Optional<SystemTenant> findTenantByPhone(Long phone) {
        return tenantRepository.findByPhone(phone);
    }

    @Override
    public List<SystemTenant> findAllTenants() {
        return tenantRepository.findAll();
    }

    @Override
    public Page<SystemTenant> findTenantsByPage(Pageable pageable) {
        return tenantRepository.findAll(pageable);
    }

    @Override
    public List<SystemTenant> findAllActiveTenants() {
        return tenantRepository.findByIsDeleted(0);
    }

    @Override
    public List<SystemTenant> findAllNormalTenants() {
        return tenantRepository.findByStatus((short) 1);
    }

    @Override
    @Transactional
    public boolean deleteTenant(Long id) {
        Optional<SystemTenant> tenantOptional = tenantRepository.findById(id);
        if (tenantOptional.isEmpty()) {
            return false;
        }
        
        SystemTenant tenant = tenantOptional.get();
        tenant.setIsDeleted(1);
        tenant.setUpdatedAt(LocalDateTime.now());
        
        tenantRepository.save(tenant);
        return true;
    }

    @Override
    @Transactional
    public void removeTenant(Long id) {
        tenantRepository.deleteById(id);
    }

    @Override
    public boolean isTenantNameExists(String name) {
        return tenantRepository.existsByName(name);
    }

    @Override
    public boolean isTenantEmailExists(String email) {
        return tenantRepository.existsByEmail(email);
    }

    @Override
    public boolean isTenantPhoneExists(Long phone) {
        return tenantRepository.existsByPhone(phone);
    }

    @Override
    public List<SystemTenant> findTenantsWithAvailableUserSlots() {
        return tenantRepository.findTenantsWithAvailableUserSlots();
    }

    @Override
    public List<SystemTenant> findTenantsExpiringInDays(int days) {
        return tenantRepository.findTenantsExpiringInDays(days);
    }

    @Override
    @Transactional
    public boolean incrementReadyUserCount(Long id) {
        Optional<SystemTenant> tenantOptional = tenantRepository.findById(id);
        if (tenantOptional.isEmpty()) {
            return false;
        }
        
        SystemTenant tenant = tenantOptional.get();
        tenant.setReadyUserCount(tenant.getReadyUserCount() + 1);
        tenant.setUpdatedAt(LocalDateTime.now());
        
        tenantRepository.save(tenant);
        return true;
    }

    @Override
    @Transactional
    public boolean decrementReadyUserCount(Long id) {
        Optional<SystemTenant> tenantOptional = tenantRepository.findById(id);
        if (tenantOptional.isEmpty()) {
            return false;
        }
        
        SystemTenant tenant = tenantOptional.get();
        if (tenant.getReadyUserCount() > 0) {
            tenant.setReadyUserCount(tenant.getReadyUserCount() - 1);
            tenant.setUpdatedAt(LocalDateTime.now());
            
            tenantRepository.save(tenant);
            return true;
        }
        
        return false;
    }
} 